import json
from bson import json_util
from flask import request, Response, render_template
from apps import  mongo
from . import operator_blue

@operator_blue.route("/tpage")
def tpage():
    """
    获取targets列表页面
    """
    return render_template("magicbook/extend.html")
    
@operator_blue.route("/targets")
def targets():
    data_center = request.args.get("__data_center", None)
    page = int(request.args.get("page", 1))
    limit = int(request.args.get("limit", 10))

    targets = mongo.db.dt_instence.find()
    count = targets.count()
    if data_center:
        # .skip(limit * (page-1)).limit(limit=limit) 实现分页
        rets = mongo.db.dt_instence.find({"__data_center": data_center}).skip(limit * (page-1)).limit(limit=limit)
    else:
        rets = targets.skip(limit * (page-1)).limit(limit=limit)
    rets = [ret for ret in rets]
    data = {"total": count, "rets": rets}
    return Response(json.dumps(data, default=json_util.default), \
                mimetype="content-type: application/json")

@operator_blue.route("/instence", methods=["POST"])
def add_instence():
    target = request.form["target"]
    datacenter = request.form["__meta_datacenter"]
    job_type = request.form["__meta_prometheus_job"]
    if not (target and datacenter and job_type):
        return {"status": 400, "msg": "absent data, add target failed!"}
    data = {
        "target" : target,
        "__meta_datacenter" : datacenter,
        "__meta_prometheus_job" : job_type
    }
    mongo.db.dt_instence.insert_one(data)
    return {"status": 200, "msg": "add target success"}